package com.code.springbootquartz.service;

import com.code.springbootquartz.jobs.DemoJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/*
 * @author: liyufei
 * @date: 2018-07-13 16:03
 */
@Service
public class JobService {

    private static final String JOB_NAME = "jobName";
    private static final String JOB_GROUP = "jobGroup";
    private static final String TRIGGER_NAME = "triggerName";
    private static final String TRIGGER_GROUP = "triggerGroup";

    @Autowired @Qualifier("Scheduler")
    private Scheduler scheduler;

    public void createTrigger(long dateTime) {
        try {
            JobDetail job = scheduler.getJobDetail(new JobKey(JOB_NAME,JOB_GROUP));
            JobDataMap jobMap = new JobDataMap();
            jobMap.put("abc", "123");
            if (null == job) {
                job = JobBuilder.newJob(DemoJob.class)
                        .withIdentity(JOB_NAME, JOB_GROUP) // name "myJob", group "group1"
                        .usingJobData(jobMap)
                        .storeDurably(true)
                        .build();
                // durable, 指明任务就算没有绑定Trigger仍保留在Quartz的JobStore中,
                scheduler.addJob(job, false);
            }
            JobDataMap triggerMap = new JobDataMap();
            triggerMap.putAsString("dateTime", dateTime);
            SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger()
                    .withIdentity(TRIGGER_NAME + UUID.randomUUID(), TRIGGER_GROUP)
                    .startAt(new Date(dateTime))
                    .usingJobData(triggerMap)
                    .forJob(JOB_NAME, JOB_GROUP)
                    .build();
            // 如下两种方式都是在服务器宕机或重启后重新执行过期的任务和即将要执行的任务。但是在服务器宕机或重启后所有触发器任务都消失了，暂未解决！！
            //((SimpleTriggerImpl)trigger).setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_SMART_POLICY);
            //trigger.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT);
            scheduler.scheduleJob(trigger);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
